﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.SessionState;
using System.Web;

namespace DotNet.Common
{
    public class SessionOperate
    {
        
        /// <summary>
        /// Session操作类
        /// </summary>
        public SessionOperate()
        { }

        //程序退出时要用 触发Session_End事件 Session.Abandon(); //这个不触发Session_End事件 Session.Clear()
        
        ///<summary>
        ///判断Session中某键值是否存在，如果不存在，输出提示信息，并且转向相应页面
        ///</summary>
        ///<param name="SessionName">Session中键名称</param>
        ///<param name="Message">提示信息</param>
        ///<param name="RedirectUrl">要转向的页面</param>
        public  void CheckSession(string SessionName, string Message, string RedirectUrl)
        {
            HttpSessionState Session = HttpContext.Current.Session;
            HttpResponse Response = HttpContext.Current.Response;
            if (Session[SessionName] == null)
            {
                WriteMessage(Message, false, false);
                string js = "top.document.location='" + RedirectUrl + "';";
                WriteJavaScript(js);
                Response.Redirect(RedirectUrl);
            }
        }

        ///<summary>
        ///以Response.Write()方式输出一条JavaScript语句
        ///</summary>
        ///<param name="strJavaScript">要输出的JavaScript语句</param>
        public void WriteJavaScript(string strJavaScript)
        {
            HttpResponse Response = HttpContext.Current.Response;
            Response.Write("<script language=javascript>" + strJavaScript + "</script>");
        }
        
        ///<summary>
        ///用Javascript的Window.alert()方法输出提示信息
        ///</summary>
        ///<param name="strMsg">要输出的信息</param>
        ///<param name="Back">输出信息后是否要history.back()</param>
        ///<param name="End">输出信息后是否要Response.end()</param>
        public void WriteMessage(string strMsg, bool Back, bool End)
        {
            HttpResponse Response = HttpContext.Current.Response;
            //将单引号替换，防止javascript出错
            strMsg = strMsg.Replace("'", "");
            //将回车换行符去掉，防止JAVASCRIPT出错
            strMsg = strMsg.Replace("\r\n", "");
            Response.Write("<script language=javascript>alert('" + strMsg + "');</script>");
            if (Back)
                Response.Write("<script language=javascript>history.back()</script>");
            if (End)
                Response.End();
        }

    }
}
